package common;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class Download
{
	/**
	 * 默认文件保存目录download
	 */
	public static String downloadDir = System.getProperty("user.dir") + File.separator + "download";

	/**
	 * 下载文件到指定目录
	 * @param url - 文件下载地址
	 * @param filePath - 保存文件目录
	 * @param fileName - 保存文件名
	 * @throws IOException
	 */
	public static void downloadFromUrl(String url, String filePath, String fileName) throws IOException
	{	
		//如果保存文件目录不存在，创建目录
		File fileTemp = new File(filePath);
		if (!fileTemp.exists())
		{
			fileTemp.mkdirs();
		}
		
		URL downloadUrl = new URL(url);  
		HttpURLConnection connnect = (HttpURLConnection)downloadUrl.openConnection();
		
        //设置超时间为30秒
		connnect.setConnectTimeout(30*1000);
		connnect.setReadTimeout(30*1000);
		
		//防止屏蔽程序抓取而返回403错误
		connnect.setRequestProperty("User-Agent",
				"Mozilla/5.0 (Windows NT 6.1; WOW64) "
				+ "AppleWebKit/537.36 (KHTML, like Gecko) "
				+ "Chrome/47.0.2526.80 Safari/537.36");

		//得到输入流
		InputStream inputStream = connnect.getInputStream();

		//从输入流中获取字节数组
		byte[] data = readInputStream(inputStream); 
		
		//校验字节大小
		long contentLength = connnect.getContentLength();
		long dataLength = data.length;
		if (contentLength != dataLength)
		{
			throw new IOException("校验字节失败");
		}
		
		//写文件
		File file = new File(filePath + File.separator + fileName);    
		FileOutputStream fileOutputStream = new FileOutputStream(file);     
		fileOutputStream.write(data); 
		
		if(fileOutputStream != null)
		{
			fileOutputStream.close();  
		}
		if(inputStream != null)
		{
			inputStream.close();
		}
	}
	
	/**
	 * 下载文件到默认download目录
	 * @param url - 文件下载地址
	 * @param fileName - 保存文件名
	 * @throws IOException
	 */
	public static void downloadFromUrl(String url, String fileName) throws IOException
	{
		downloadFromUrl(url, downloadDir, fileName);
	}
	
	/**
	 * 从输入流中获取字节数组
	 * @param inputStream - 输入流
	 * @return 获取的字节数组
	 * @throws IOException
	 */
	private static byte[] readInputStream(InputStream inputStream) throws IOException
	{
		byte[] buffer = new byte[1024];
		int len = 0;
		ByteArrayOutputStream byteArrayOs = new ByteArrayOutputStream();
		while ((len = inputStream.read(buffer)) != -1)
		{
			byteArrayOs.write(buffer, 0, len);
		}
		byteArrayOs.close();
		return byteArrayOs.toByteArray();
	}
}
